import string
import random

from django.contrib.auth import get_user_model, login, logout
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.http import require_http_methods

from zlauth.forms import RegisterForm, LoginForm
from zlauth.models import CaptchaModel
# from django.contrib.auth.models import User

User = get_user_model()


# Create your views here.
@require_http_methods(['POST', 'GET'])
def zlLogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember_me = form.cleaned_data.get('remember_me')
            print(f"---email:{email}---password:{password}---remember_me:{remember_me}")
            user = User.objects.get(email=email)
            if user.check_password(password):
                # 登录
                login(request, user)
                # 判断是否需要记住我
                if not remember_me:
                    # 如果没有点击记住我，那么就要设置过期时间为0，即浏览器关闭后就会过期
                    request.session.set_expiry(0)
                    # 如果点击了，那么就什么都不做，使用默认的2周的过期时间
                return redirect('blog:index')
            else:
                print('邮箱或者密码错误')
                form.add_error('email', '邮箱或者密码错误')
                return render(request, 'login.html',context={'form':form})
                # return redirect(reverse('zlauth:login'))


def zlLogout(request):
    logout(request)
    return redirect('blog:index')

@require_http_methods(['POST', 'GET'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            print(f"email:{email}, username:{username}, password:{password}")
            User.objects.create_user(username=username, email=email, password=password)
            return redirect(reverse('zlauth:login'))
        else:
            print(form.errors)
            # 重新跳转到注册页面
            return redirect(reverse('zlauth:register'))
            # form.add_error("")
            # return render(request, 'register.html', {'form': form})


def send_email_captcha(request):
    email = request.GET.get('email')
    if email:
        # 生成验证码（随机4位阿拉伯数字）
        num_list = random.sample(string.digits, 4)
        captcha = ''.join(num_list)
        # 存入数据库（更新或者保存）
        CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})
        print(f'captcha: {captcha}')
        send_mail("知了博客注册验证码", message=f"您的注册验证码是:{captcha},有效期5分钟", recipient_list=[email],
                  from_email=None)
        result = {
            'code': 200,
            'msg': '成功'
        }
        return JsonResponse(result)
    else:
        result = {
            'code': 400,
            'msg': '失败'
        }
        return JsonResponse(result)
